package com.fly.demo.aspect;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import com.fly.core.exception.ValidateException;
import com.fly.core.utils.HttpServletUtils;
import com.fly.demo.aspect.annotation.AuthToken;
import com.fly.demo.service.TokenService;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Aspect
@Order(0)
@Component
public class AuthTokenAspect
{
    @Autowired
    List<TokenService> tokenServices;
    
    /**
     * 使用AuthToken注解标注的类
     * 
     */
    @Before("@annotation(authToken)")
    public void doBefore(JoinPoint joinPoint, AuthToken authToken)
    {
        HttpServletRequest request = HttpServletUtils.getRequest();
        if (request == null)
        {
            log.error("AuthToken注解使用错误，当前请求非web请求");
        }
        log.info("开始执行鉴权检查");
        String token = request.getHeader("token");
        if (!valide(token))
        {
            throw new ValidateException("对不起，您无权访问该接口，请检查token参数");
        }
    }
    
    /**
     * 任意一个通过校验
     * 
     * @param token
     * @return
     */
    private boolean valide(String token)
    {
        return tokenServices.stream().anyMatch(t -> t.valide(token));
    }
}